<template>
  <div class="home">
    <van-nav-bar
      title="每日健康填报"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- <van-nav-bar
      class="blue"

      title="社区自主报备"
    >
    </van-nav-bar> -->

    <img src="../../assets/images/xyyqfk.png" />
    <van-form validate-first @submit="onSubmit">
      <!-- <div block type="info" class="get-area" @click="testNfc" >刷卡读取身份证信息</div> -->
      <!-- 通过 pattern 进行正则校验 -->

      <!-- <van-field input-align="right" name="radio" label="填报用户类型">
        <template #input>
          <van-radio-group v-model="formData.userType" direction="horizontal">
            <van-radio name="0">本人信息</van-radio>
            <van-radio name="1">共同居住人</van-radio>
          </van-radio-group>
        </template>
      </van-field> -->

      <div
        v-for="(item, index) in addManForm.formData"
        :model="addManForm"
        :key="index"
      >
        <van-field
          input-align="right"
          label="学生姓名"
          v-model="addManForm.formData[index].name"
          @focus="showSex = true"
          name="pattern"
          placeholder="请填写学生姓名"
          :rules="[{ required: true, message: '请输入正确内容' }]"
        />

        <van-field
          input-align="right"
          label="身份证号"
          v-model="addManForm.formData[index].cardno"
          name="pattern"
          placeholder="请填写身份证号"
          :rules="[{ required: true, message: '请输入正确内容' }]"
          maxlength="18"
        />

        <van-field
          input-align="right"
          label="身体异常状况"
          @focus="
            showHealthAbnormalInfo = true
            selectedIndex = index
          "
          v-model="
            addManForm.formData[index].healthConditionBean
              .healthAbnormalInfoName
          "
          name="pattern"
          placeholder="请输入身体异常状况"
        />
        <van-popup v-model="showHealthAbnormalInfo" position="bottom">
          <van-picker
            show-toolbar
            value-key="name"
            :columns="showHealthAbnormalInfoColumns"
            @cancel="showHealthAbnormalInfo = false"
            @confirm="val => onShowHealthAbnormalInfoConfirm(index, val)"
          />
        </van-popup>
        <van-field
          input-align="right"
          label="体温"
          v-model="addManForm.formData[index].healthConditionBean.temperature"
          name="pattern"
          placeholder="请输入体温"
        />
        <van-field input-align="right" name="radio" label="健康码颜色">
          <template #input>
            <van-radio-group
              v-model="
                addManForm.formData[index].healthConditionBean.healthCodeColor
              "
              direction="horizontal"
            >
              <van-radio name="0">绿码</van-radio>
              <van-radio name="1">黄码</van-radio>
              <van-radio name="2">红码</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field input-align="right" name="radio" label="是否接触过疑似病例">
          <template #input>
            <van-radio-group
              v-model="
                addManForm.formData[index].healthConditionBean
                  .isContactSuspectedPatients
              "
              direction="horizontal"
            >
              <van-radio name="1">是</van-radio>
              <van-radio name="0">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field input-align="right" name="radio" label="是否接触过确诊病例">
          <template #input>
            <van-radio-group
              v-model="
                addManForm.formData[index].healthConditionBean
                  .isContactDiagnosedPatients
              "
              direction="horizontal"
            >
              <van-radio name="1">是</van-radio>
              <van-radio name="0">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          input-align="right"
          name="radio"
          label="14天内是否途经重点关注地区"
        >
          <template #input>
            <van-radio-group
              v-model="
                addManForm.formData[index].healthConditionBean
                  .isThroughFocusArea14
              "
              direction="horizontal"
            >
              <van-radio name="1">是</van-radio>
              <van-radio name="0">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-row>
          <van-col span="24"
            ><p style="font-size: 17px">
              &nbsp;&nbsp;&nbsp;健康码、通信行程卡、48小时内核酸检测报告
            </p></van-col
          >
        </van-row>
        <van-field input-align="right" name="radio" label="">
          <template #input>
            <div
              :class="
                addManForm.formData[index].healthConditionBean.postData.length >
                2
                  ? 'upload-img-5'
                  : 'upload-img-1'
              "
            >
              <div class="posting-uploader">
                <div
                  class="posting-uploader-item"
                  v-for="(item, nn) in addManForm.formData[index]
                    .healthConditionBean.postData"
                  :key="nn"
                >
                  <img :src="item.content" alt="图片" class="imgPreview" />
                  <van-icon
                    name="close"
                    @click="delImg(index, nn)"
                    class="delte"
                  />
                </div>
                <van-uploader
                  :after-read="val => onRead(index, val)"
                  :accept="'image/*'"
                  v-show="
                    addManForm.formData[index].healthConditionBean.postData
                      .length <= 2
                  "
                >
                  <!-- <img src="../../assets/img/img1.png" alt="等待传图" class="imgPreview"> -->
                  <!-- <img src="" alt="等待传图" class="imgPreview"> -->
                </van-uploader>
              </div>
            </div>
          </template>
        </van-field>
      </div>
      <div style="margin: 16px; display: flex">
        <van-button block type="info" native-type="submit">确认</van-button>
      </div>
      <div style="margin: 16px"></div>
    </van-form>
    <!-- 省市区弹出 -->
    <van-popup
      v-model="show"
      closeable
      position="bottom"
      :style="{ height: '100%' }"
    >
      <div class="title">上车{{ title }}</div>
      <div class="container">
        <div
          class="item"
          v-for="(item, index) in forArea"
          :key="index"
          @click="checkoutArea(item)"
        >
          {{ item.name || item }}
        </div>
      </div>
    </van-popup>

    <!-- 证件类型 -->
    <van-popup v-model="showCertificate" round position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @cancel="showCertificate = false"
        @confirm="onConfirm"
      />
    </van-popup>
    <!-- 社区code -->
    <van-popup v-model="showCode" round position="bottom">
      <van-picker
        show-toolbar
        :columns="showCodeColumns"
        value-key="name"
        @cancel="showCode = false"
        @confirm="onCodeConfirm"
      />
    </van-popup>
    <!-- 日期 -->
    <van-popup v-model="showDate" round position="bottom">
      <van-datetime-picker
        @confirm="getConfirm"
        @cancel="showDate = false"
        :min-date="minDate"
        type="date"
        title="选择年月日"
      />
    </van-popup>
  </div>
</template>

<script>
import { areaList } from '@vant/area-data'
import area from '@/libs/area.json'
import { everDayFillIn, getAllForFillIn } from '@/api/student/register'
import { Toast, Dialog } from 'vant'
import { destinationByCity } from '@/api/self/record'

export default {
  data() {
    return {
      selectedIndex: '',
      disabled: false,
      seat_number: '', // 座位号
      range_number: '', // 班次
      emergency_contact_name: '', // 紧急联系人姓名
      emergency_contact_mobile: '', // 紧急联系人电话
      trave_mode: '', // 出行交通方式（0飞机 1火车 2轮渡  3自驾  4客运
      estimated_arrival_date: '', // 预计抵达日期
      showTwoLabel: '',
      goDlShow: false,
      checked: false,
      showArea: false,
      showArea2: false,
      canSelectCommunity: false,
      areaList,
      minDate: new Date(1900, 0, 1),
      showDate: false, // 选择生日
      seat_number_label: '',
      range_label: '',
      label: '身份证号',
      trave_columns: ['飞机', '火车', '轮渡', '自驾', '客运'],

      columns: ['身份证', '护照', '军官证', '港澳通行证'],

      showHealthAbnormalInfoColumns: [
        { name: '健康', value: '0' },
        { name: '咳嗽', value: '1' },
        { name: '流鼻涕', value: '2' },
        { name: '发烧', value: '3' },
        { name: '疑似', value: '4' },
        { name: '确诊', value: '5' }
      ],
      showCodeColumns: [],
      showTrave: false, // 出行交通方式类型
      sexColumns: ['小明', '小红'],
      addManForm: {
        formData: [
          {
            userType: '0',
            userId: '',
            healthAbnormalInfoName: '', // '身体异常状况 \n0健康 1咳嗽 2流鼻涕 3发烧 4疑似 5确诊',
            healthAbnormalInfo: '', // '身体异常状况 \n0健康 1咳嗽 2流鼻涕 3发烧 4疑似 5确诊',
            healthCodeColor: '0', // '健康码颜色 0绿色 1黄色  2红色',
            isContactSuspectedPatients: '0', // 是否接触过疑似病例   0 否  1 是
            isContactDiagnosedPatients: '0', // 是否接触过确诊病例   0 否  1 是
            isThroughFocusArea14: '0', // 14天内是否途经重点关注地区  0 否  1 是
            temperature: '', // 体温
            postData: []
          }
        ]
      },
      forArea: area,
      Province: '', // 省
      city: '', // 市
      area: '', // 区
      title: '省', // 标题省  市  区
      show: false, // 城市选择
      pickerShow: false, // 时间选择
      isGetArea: false, // 是否已经获取上车省市区
      showCode: false, // 社区code
      showCertificate: false, // 证件类型
      showSex: false, // 性别类型
      showHealthAbnormalInfo: false, // 身体异常状况
      phoneRules: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
      postData: []
    }
  },
  mounted() {
    // if (this.$route.query.code == null) {
    //   this.disabled = true
    // } else if (this.$route.query.code == '') {
    //   this.disabled = true
    // } else if (
    //   this.$route.query.code != null &&
    //   this.$route.query.codename != null
    // ) {
    //
    //   this.disabled = true
    // }
    this.getCodeName(this.$route.query.code)
  },
  methods: {
    getCodeName(code) {
      if (this.$route.query.codename == null) {
        getAllForFillIn(this.$route.query.familyId).then(res => {
          Toast.clear()
          if (res.data.errcode === 0) {
            this.addManForm.formData = res.data.data
            console.log('init======', res.data.data)
          } else {
            Toast.fail(res.data.msg)
          }
        })
      }
    },
    delImg(index, k) {
      // 删除指定下标的图片对象
      // if (isNaN(index) || index >= this.addManForm.formData[index].postData[i].length) {
      //   return false
      // }
      // let tmp = []
      // for (let k = 0, len = this.addManForm.formData[index].postData[i]; k < len; k++) {
      //   if (this.addManForm.formData[index].postData[k] !== this.addManForm.formData[index].postData[i]) {
      //     tmp.push(this.addManForm.formData[index].postData[i])
      //   }
      // }
      // this.addManForm.formData[index].postData = tmp
      if (
        isNaN(k) ||
        k >= this.addManForm.formData[index].healthConditionBean.postData.length
      ) {
        return false
      }
      let tmp = []
      for (
        let i = 0,
          len = this.addManForm.formData[index].healthConditionBean.postData
            .length;
        i < len;
        i++
      ) {
        if (
          this.addManForm.formData[index].healthConditionBean.postData[i] !==
          this.addManForm.formData[index].healthConditionBean.postData[k]
        ) {
          tmp.push(
            this.addManForm.formData[index].healthConditionBean.postData[i]
          )
        }
      }
      this.addManForm.formData[index].healthConditionBean.postData = tmp
    },
    onRead(index, file) {
      // 上传图片到图片服务器
      this.addManForm.formData[index].healthConditionBean.postData.push(file) // postData是一个数组
      // let url = API + '/upload?type=99'
      // let fd = new FormData()
      // fd.append('upImgs', file.file)
      // this.axios.post(url, fd, {headers: {
      //   'Content-Type': 'multipart/form-data'
      // }}).then(res => {
      //   this.imgUrlListValue.push(res.data.urls[0].image) //这里上传到指定的图片服务器，成功后会返回图片的url
      // }).catch(err => {
      //   alert(err)
      // })
    },
    getConfirm(value) {
      let yy = new Date(value).getFullYear()
      let mm = new Date(value).getMonth() + 1
      let dd = new Date(value).getDate()
      this.formData.bithday = yy + '-' + mm + '-' + dd
      this.showDate = false
    },
    onCodeConfirm(value) {
      this.formData.codename = value.name
      this.showCode = false
    },
    onAreaConfirm(value) {
      console.log('=====value=======', value)
      this.showArea = false
      this.formData.start_addr_list = value
        .filter(item => !!item)
        .map(item => item.name)
        .join('/')
    },
    enAreaConfirm(value) {
      console.log('=====value=======', value)
      this.showArea2 = false
      this.formData.end_addr_list = value
        .filter(item => !!item)
        .map(item => item.name)
        .join('/')
      console.log(this.$route.query.code == null)

      console.log(this.$route.query.codename == null)
      if (
        this.$route.query.code == null ||
        this.$route.query.codename == null
      ) {
        let endAdd = { name: this.formData.end_addr_list }
        destinationByCity(endAdd).then(res => {
          if (res.data.errcode === 0) {
            this.showCodeColumns = res.data.data
          } else {
            Toast.fail(res.data.msg)
          }
        })
      }
    },
    goDlConfirm(value) {
      const formatDate = value =>
        `${value.get}/${value.getMonth() + 1}/${value.getDate()}`
      let yy = new Date(value).getFullYear()
      let mm = new Date(value).getMonth() + 1
      let dd = new Date(value).getDate()
      this.formData.estimated_arrival_date = yy + '-' + mm + '-' + dd
      this.goDlShow = false
    },
    onConfirm(value) {
      this.label = value
      this.formData.card_type = value
      this.showCertificate = false
    },
    onSexConfirm(value) {
      this.label = value
      this.formData.sex = value
      this.showSex = false
    },
    onShowHealthAbnormalInfoConfirm(index, value) {
      // console.log(this.addManForm.formData[this.selectedIndex].healthConditionBean)
      this.addManForm.formData[
        this.selectedIndex
      ].healthConditionBean.healthAbnormalInfoName = value.name
      this.addManForm.formData[
        this.selectedIndex
      ].healthConditionBean.healthAbnormalInfo = value.value
      this.showHealthAbnormalInfo = false
    },
    testNfc() {
      // 测试用户终端
      let u = navigator.userAgent
      let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
      let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

      if (isAndroid) {
        Toast.loading({
          message: '正在识别...',
          forbidClick: true,
          duration: 20000
        })
        window.Android.useNFCReadIdCard('123')
      }
      if (isiOS) {
        return Toast.fail('抱歉\n暂不支持ios')
      }
    },
    onSubmit() {
      // if (this.checked == false) {
      //   Toast.fail('请确认报备内容正确属实')
      //   return
      // }
      // formdata.sex = this.formData.sex == '男' ? 1 : 0
      // formdata.companion_id = this.$route.query.id
      // // formdata.avenue_flow_area = formdata.avenue_flow_area == '1' ? '是' : '否'
      // formdata.uploader = this.postData

      // Toast.loading({
      //   message: '加载中...',
      //   forbidClick: true,
      //   duration: 10000,
      // })
      console.log(this.addManForm.formData)
      everDayFillIn(this.addManForm.formData).then(res => {
        Toast.clear()
        if (res.data.errcode === 0) {
          Dialog.alert({
            message: '提交成功',
            showCancelButton: false,
            showConfirmButton: false
          }).then(() => {})
          const TIMEOUT = setTimeout(() => {
            Dialog.close()
            clearTimeout(TIMEOUT)
          }, 2000)
          this.$router.push({
            name: 'student-menu',
            query: {}
          })
        } else {
          this.$router.push({
            name: 'student-menu',
            query: {}
          })
          // alert(1)
          // Toast.fail(res.data.msg)
        }
      })
    },
    checkoutArea(item) {
      if (!this.Province) {
        // 选择省
        this.Province = item.name
        this.forArea = item.child
        this.title = '市'
      } else if (!this.city) {
        // 选择市
        this.city = item.name
        this.forArea = item.child
        this.title = '区'
      } else if (!this.area) {
        // 选择区
        this.area = item
        this.show = false
        this.title = '省'
        // 拼接省市区 展示页面
        this.formData.start_station_addr =
          this.Province + '/' + this.city + '/' + this.area

        this.forArea = area
        // 清空省市区 为了下一次选择省市区
        this.Province = ''
        this.city = ''
        this.area = ''
      }
    }
  }
}
</script>
<style lang="less" scoped>
.upload-img-5 {
  margin: 5px 0 90px 0;
}

.upload-img-1 {
  margin: 5px 0 15px 0;
}

.home {
  background: url('../../assets/images/smtb.jpg') no-repeat;
  height: 100%;
  img {
    // background: url('../../assets/images/smtb.jpg');
    width: 100%;
  }

  .dialog-container {
    height: 70vh;
    overflow-y: auto;
  }

  .get-area {
    width: 100%;
    padding: 0 0.8rem;
    font-size: 0.747rem;
    color: #fff;
    background-color: #1989fa;
    border: 0.053rem solid #1989fa;
    height: 2.347rem;
    line-height: 2.347rem;
    text-align: center;
    border-radius: 0.107rem;
    cursor: pointer;
    box-sizing: border-box;
    margin-right: 10px;
  }

  /deep/ .van-field__label {
    width: 8em;
  }

  /deep/ .van-field__error-message {
    text-align: right;
  }

  .title {
    // font-size: 28px;
    text-indent: 20px;
    padding: 50px 0 20px;
  }

  .container {
    width: 90%;
    height: 80vh;
    overflow-y: auto;
    border: 1px solid #adadad;
    margin: auto;

    .item {
      margin: 10px;
    }
  }
}

.up-and-down {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f1f3f4;
  height: 80px;
  color: #333;
}

.home .blue {
  background-color: transparent;
}

.home .van-cell {
  background-color: transparent;
}

input.van-field__control::-webkit-input-placeholder {
  color: #4d6ff0;
}
</style>
